package cn.wizzer.app.web.commons.ext.websocket.action.msg.group;

import cn.wizzer.app.user.modules.models.GroupInfo;
import cn.wizzer.app.user.modules.models.GroupMember;
import cn.wizzer.app.user.modules.models.vo.ChatUserVO;
import cn.wizzer.app.user.modules.services.GroupInfoService;
import cn.wizzer.app.user.modules.services.GroupMemberService;
import cn.wizzer.app.web.commons.ext.websocket.filter.TokenFilter;
import cn.wizzer.app.web.commons.ext.websocket.main.action.BaseNettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.action.NettyAction;
import cn.wizzer.app.web.commons.ext.websocket.main.base.NettyCache;
import cn.wizzer.app.web.commons.ext.websocket.main.result.ChatResult;
import cn.wizzer.app.web.commons.utils.NettyMsgUtil;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.util.param.Param;
import cn.wizzer.framework.util.param.Param4Map;
import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSONObject;
import io.netty.channel.Channel;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

/**
 * @author zl
 * @date 2020/6/5 15:25
 */
@IocBean
@NettyAction(uri = "/group/del/member", filters = {TokenFilter.class})
public class GroupDelMemberAction extends BaseNettyAction {

    @Inject
    @Reference
    private GroupInfoService groupInfoService;

    @Inject
    @Reference
    private GroupMemberService groupMemberService;

    @Override
    public Result action(Channel income,
                         @Param4Map(fields = {@Param(name = "groupId", required = true),
                                 @Param(name = "userId", required = true)}) JSONObject params) {
        ChatUserVO self = NettyCache.globalGet(params.get("appid"));
        String groupId = params.getString("groupId");
        String userId = params.getString("userId");
        if (self.getId().equals(userId)) {
            Result.breakWith("移除失败，不能移除自己");
        }
        GroupInfo groupInfo = groupInfoService.fetch(Cnd.where("id", "=", groupId).and("masterId", "=", self.getId()));
        if (groupInfo == null) {
            Result.breakWith("移除失败，你不是群主或群组不存在");
        }
        GroupMember groupMember = groupMemberService.fetch(Cnd.where("groupId", "=", groupId).and("userId", "=", userId).and("delFlag", "=", 0));
        if (groupMember == null) {
            Result.breakWith("该成员已不在群里");
        }
        //移除群成员
        groupMemberService.delMember(self.getId(), userId, groupId);
        //若被移除用户在线则通知用户
        ChatUserVO beInvitedUser = NettyCache.globalGet(userId);
        if (beInvitedUser != null) {
            String content = "您已被移除群 " + groupInfo.getGroupName();
            NettyMsgUtil.send(beInvitedUser.getChannel(), ChatResult.MessageTypeEnum.SYSTEM, ChatResult.ActionEnum.LEAVE, self, content);
        }
        return Result.success();
    }
}
